//
// Created by LiuYou on 2021/8/2.
//
/**
 * @brief 随意指出一个文件, 计算这个文件中有多少个字符。
 */


#include <cstdlib>
#include <cstdio>
#include <sys/mman.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>


int main(int argc, char** argv) {
    if (argc < 2) {
        std::fprintf( stderr, "Usage...\n" );
        std::exit( 1 );
    }

    int fd = open( argv[1], O_RDONLY );
    if (fd < 0) {
        std::perror( "open()" );
        std::exit( 1 );
    }

    struct stat statResult;
    if (fstat( fd, &statResult ) < 0) {
        std::perror( "fstat()" );
        std::exit( 1 );
    }

    void* str = mmap( nullptr, statResult.st_size, PROT_READ, MAP_PRIVATE, fd, SEEK_SET );
    char* string = static_cast<char*>(str);
    if (string == MAP_FAILED) {
        std::perror( "mmap()" );
        std::exit( 1 );
    }
    close( fd );

    int count = 0;
    for (int i = 0; i < statResult.st_size; ++i) {
        if (string[i] == 'a') {
            ++count;
        }
    }

    std::fprintf( stdout, "%d\n", count );


    munmap( str, statResult.st_size );
    std::exit( 0 );
}